<template>
  <div ref="login" id="login" tabindex="10" :style="{'background-image': 'url('+backgroundImage+')','padding': padding}" @keydown="handleEnter">
    <div class="login-container" :style="{width: width, height: height}">
      <section class="login-header">
        <img class="logo" :src="logo" alt="logo">
      </section>

      <section class="login-body" ref="loginBody">
        <div class="login-img">
          <img v-if="loginImgShow" :src="loginImg" alt="图片" :style="{'max-width': maxWidth}">
        </div>
        <div class="form-wrap">
          <div>
            <p class="appName">{{ appName }}</p>
            <p>用户登录</p>
            <Form class="login-form" ref="loginForm" :model="loginData" :rules="rules">
              <FormItem prop="username">
                <i-input v-model="loginData.username" placeholder="请输入手机号（账号）" icon="ios-person-outline"></i-input>
              </FormItem>
              <FormItem prop="password" class="pwFormItem" :class="{'login-err-pw-formitem': isError}">
                <i-input type="password" v-model="loginData.password" placeholder="请输入密码" icon="ios-lock-outline"></i-input>
              </FormItem>
              <FormItem>
                <div class="login-err" v-if="isError"><Icon type="ios-alert-outline" />{{ errText }}</div>
                <Button class="btn" type="primary" @click="submitForm" :loading="loginLoading">登录</Button>
                <div class="forget-passwd-wrap">
                  <span class="forget-passwd">
                    <Icon type="ios-help-circle-outline"/>
                    <span>忘记密码</span>
                  </span>
                </div>
              </FormItem>
            </Form>
          </div>
        </div>
      </section>

      <!-- footer -->
      <footer class="footer"><p>{{ app.copyName }} Copyright Reserved</p></footer>
    </div>
  </div>
</template>


<script>
import mixins from '@/mixins'
import axios from 'axios'
import appConf from '@/lib/app.js'
let Base64 = require("js-base64").Base64;

export default {
  name: "login-component",
  props: {
    // 网站logo
    logo: {
      type: String,
      default: "/static/images/logo-primary-large.png"
    },
    // 登录框插画
    loginImg: {
      type: String,
      default: "/static/images/login-img.png"
    },
    // 背景图片地址
    backgroundImage: {
      type: String,
      default: "/static/images/login-bg.png"
    },
    // 系统名称
    appName: {
      type: String,
      default: appConf.appName
    },
    // 后台登录接口
    loginUrl: String,
    // 是否自己处理回调
    delResponse: {
      type: Boolean,
      default: false
    }
  },
  mixins: [mixins()],
  data() {
    return {
      loginData: {
        grant_type: 'password',
        username: null,
        password: null,
      },
      isError: false,
      errText: '',
      rules: {
        username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }]
      },
      loginLoading: false,
      maxWidth: '',
      loginImageWidth: 0,
      loginImageHeight: 0,
      loginImgShow: false,
      padding: '',
      width: '',
      height: ''
    };
  },
  created() {
    let img = new Image()
    img.src = this.loginImg
    img.onload = () => {
      this.loginImageWidth = img.width
      this.loginImageHeight = img.height
      // console.log(this.loginImageWidth, this.loginImageHeight)
      this.initImage()
    }
    window.addEventListener('resize', () => {
      this.initImage()
    })
  },
  mounted() {},
  methods: {
    loginBoxInit() {
      if (document.documentElement.clientHeight * .68 * 17 / 9 < (document.documentElement.clientWidth - 50)) {
        this.height = document.documentElement.clientHeight * .68 + 'px'
        this.width = document.documentElement.clientHeight * .68 < 440 ? 440 * 17 / 9 + 'px' : document.documentElement.clientHeight * .68 * 17 / 9 + 'px'
      } else {
        this.height = '68%'
        this.width = '82%'
      }
    },
    initImage() {
      this.$nextTick(() => {
        if (!this.$refs['loginBody']) return
        let loginBody_height = this.$refs['loginBody'].offsetHeight
        // console.log(loginBody_height)
        this.maxWidth = loginBody_height * parseInt(this.loginImageWidth) / parseInt(this.loginImageHeight) + 'px'
        this.loginImgShow = true
        // console.log(this.maxWidth)
      })
    },
    handleEnter(e) {
      if (e.which === 13) {
        this.submitForm()
      } else {
        return
      }
    },
    submitForm() {
      this.$refs["loginForm"].validate(valid => {
        if (valid) {
          this.loginLoading = true
          if (this.loginUrl) {
            axios.post(this.loginUrl, this.loginData).then((res) => {
              if (this.delResponse) {
                this.$emit('loginSuccss', res)
              } else {
                let redirect = decodeURIComponent(this.$route.query.redirect);
                if (redirect === 'undefined' || redirect === '/') {
                  redirect = '/home';
                }
                this.$router.push({
                  path: redirect
                });
              }
            }).catch((err) => {
              if (err.response.status === 504) {
                this.notice('error', '服务器已宕机,请重启服务器!')
              } else {
                this.notice('error', err.response.data.error_description)
              }
            })
          } else {
            this.$store.dispatch('login', this.loginData).then((res) => {
              this.loginLoading = false
              let redirect = decodeURIComponent(this.$route.query.redirect);
              if (redirect === 'undefined' || redirect === '/') {
                redirect = '/home';
              }
              this.$router.push({
                path: redirect
              });
            }).catch((err) => {
              this.loginLoading = false
              this.isError = true
              if (err.response) {
                if (err.response.data.error_description) {
                  this.errText = err.response.data.error_description
                } else {
                  switch(err.response.status) {
                    case 500: 
                      this.errText = '服务器出错!'
                      break
                    case 504:
                      this.errText = '与服务器连接超时!'
                      break
                    default: 
                      // this.errText = err.response.data.error_description
                      break
                  }
                }
              } else {
                this.errText = '与服务器连接超时!'
              }
            })
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
@import "../../theme/color.less";
@REM: 10/16;

#login {
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;
  height: 100%;
  // padding: @paddingHeight 9%;
  // padding: 0 9%;
  background-position: center, center;
  background-repeat: no-repeat;
  background-size: cover;

  .login-container {
    display: flex;
    flex-direction: column;
    position: relative;
    width: 82%;
    height: 78%;
    min-height: 440px;
    overflow: hidden;
    background-color: #fff;
    border-radius: 44px;
    // padding: @REM*8rem 0;
    margin: 0 auto;
    align-items: center;
    flex-direction: row;

    .login-header {
      padding: 0 7%;
      position: absolute;
      top: @REM*3rem;
      // margin-bottom: @REM*2rem;
      .logo {
        display: inline-block;
        height: @REM*5.5rem;
      }
    }

    .login-body {
      display: flex;
      align-items: center;
      // justify-content: space-between;
      // flex: 1;
      // padding: 20px 30px 50px 50px;
      padding: 0 12% 0 0;
      height: 64%;
      width: 100%;

      .login-img {
        display: flex;
        align-items: center;
        justify-content: center;
        flex: 1;
        // margin-right: @REM*4rem;
        padding: 0 7%;
        // position: relative;
        // top: -10px;
        
        img {
          width: 80%;
        }
      }

      .form-wrap {
        // display: flex;
        // align-items: center;
        // flex: 2;
        padding: 10px 0px;
        float: right;

        > div {
          height: auto;
        }

        p {
          color: #323232;
        }

        p.appName {
          font-size: @REM*2.4rem;
          font-weight: 700;
          margin-bottom: @REM*.6rem;
        }

        p:nth-child(2) {
          font-size: @REM*1.6rem;
        }

        .login-form {
          width: @REM*22rem;
          margin-top: @REM*2rem;

          .login-err-pw-formitem {
            margin-bottom: 0;
          }

          .login-err {
            line-height: 1.2;
            color: @error-color;
            margin: @REM*1rem 0;
            transition: all .2s;

            > i {
              font-size: @REM*1.4rem;
              position: relative;
              top: -@REM*.1rem;
            }
          }

          .btn {
            width: 100%;
          }

          .forget-passwd-wrap {
            padding: @REM*.5rem 0;
            text-align: right;
            line-height: 1;

            .forget-passwd {
              &:hover {
                cursor: pointer;
              }

              i,
              span {
                vertical-align: middle;
                line-height: 1;
              }

              i {
                font-size: @REM*1.6rem;
                color: @primary-color;
              }
            }
          }
        }
      }
    }

    .footer {
      position: absolute;
      bottom: @REM*2.5rem;
      width: 100%;
      text-align: center;
      padding: 0 @REM*2rem;

      > p {
        font-size: @REM*1.3rem;
        white-space: normal;
      }
    }
  }
}

@media screen and (max-width: 750px) {
  #login .login-container {
    border-radius: @REM*2.4rem;
  }

  #login .login-container .login-body {
    justify-content: center;
    text-align: center;
  }

  .login-body {
    padding: 0 12% !important;

    > .login-img {
      display: none !important;
    }
  }

  #login .login-container .footer {
    bottom: @REM*2rem;
  }
}
</style>

<style lang="less">
@REM: 10/16;
#login {
  .ivu-form-item {
    margin-bottom: @REM*2.4rem;

    .ivu-form-item-content {
      line-height: @REM*3.2rem;
      font-size: @REM*1.2rem;
    }
  }

  .ivu-input-wrapper {
    .ivu-input-icon {
      left: 0;
      width: @REM*3.2rem;
      height: @REM*3.2rem;
      line-height: @REM*3.2rem;
      font-size: @REM*1.6rem;
    }
  }

  .ivu-input {
    padding-left: @REM*3.2rem;
    padding-right: @REM*.7rem;
    height: @REM*3.2rem;
    font-size: @REM*1.2rem;
    border-radius: @REM*.4rem;
  }

  .ivu-btn {
    span {
      font-size: @REM*1.2rem;
    }
  }
}
</style>